package com.kasax.plugin.app.transform

import com.android.build.api.transform.*
import com.android.build.gradle.internal.pipeline.TransformManager
import com.android.utils.FileUtils
import com.kasax.plugin.app.LogUtils
import com.kasax.plugin.app.javassist.MyToastInjectByJavassist
import org.gradle.api.Project

/**
 * https://juejin.cn/post/6914485867029463054
 */
class NewInjectTransform extends Transform {
    Project project

    NewInjectTransform(Project project) {
        this.project = project
    }

    @Override
    String getName() {
        return "NewInjectTransform"
    }

    @Override
    Set<QualifiedContent.ContentType> getInputTypes() {
        return TransformManager.CONTENT_CLASS
    }

    @Override
    Set<? super QualifiedContent.Scope> getScopes() {
        return TransformManager.SCOPE_FULL_PROJECT
    }

    @Override
    boolean isIncremental() {
        return false
    }

    @Override
    void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException {
        super.transform(transformInvocation)

        LogUtils.d(getName(), "------------ ------------  transform 开始  ------------ ------------  ")


        def inputs = transformInvocation.inputs
        def outputProvider = transformInvocation.outputProvider
        inputs.each { TransformInput transformInput ->
            // 包含我们手写的 Class 类及 R.class、BuildConfig.class 等
            transformInput.directoryInputs.each { DirectoryInput directoryInput ->
                def filePath = directoryInput.file.absolutePath
                LogUtils.d(getName(), "file-path: $filePath")
                MyToastInjectByJavassist.injectToast(filePath, project)
                def destFile = outputProvider.getContentLocation(
                        directoryInput.name,
                        directoryInput.contentTypes,
                        directoryInput.scopes,
                        Format.DIRECTORY
                )
                FileUtils.copyDirectoryToDirectory(directoryInput.file, destFile)
            }

            // jar文件，如第三方依赖
            transformInput.jarInputs.each { JarInput jarInput ->
                def jarFile = outputProvider.getContentLocation(
                        jarInput.name,
                        jarInput.contentTypes,
                        jarInput.scopes,
                        Format.JAR
                )
                handleJar(jarInput.file, jarFile)
            }
        }
        LogUtils.d(getName(), "------------ ------------  transform 结束  ------------ ------------  ")
    }

    void handleJar(File jarFile, File outPutFile) {
        LogUtils.d(getName(), "handleJar source-file-path: $jarFile.absolutePath , dest-file-path: $outPutFile.absolutePath")
        FileUtils.copyFile(jarFile, outPutFile)
    }
}